package com.leyou.auth.interceptors;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private final JwtUtils jwtUtils;


    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    //重写默认方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            //获取cookie中token
            String token = CookieUtils.getCookieValue(request, "KY_TOKEN");
            System.out.println("token = " + token);
            //解析token获取到用户信息
            Payload payload = jwtUtils.parseJwt(token);
            UserDetail userDetail = payload.getUserDetail();

            log.info("用户{}正在访问拦截器,生成全局用户。",userDetail.getUsername());

            //存储一个用户到当前线程,全局用户
            UserContext.setUser(userDetail);

            return true;
        }  catch (JwtException e) {
            throw new LyException("JWT无效或过期!", e, 401);
        } catch (IllegalArgumentException e){
            throw new LyException("用户未登录!", e, 401);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 业务结束后，清理线程中的用户信息
        UserContext.removeUser();
    }
}
